package util.baidu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class NetworkCaughtUtil {

	private static URLConnection connection = null;
	private static Map<String, List<String>> headerFields = null;// 所有响应头字段

	@SuppressWarnings("static-access")
	public static JSONObject sendGETReturnJSON(String url) {
		return new JSONObject().parseObject(sendHttpRequest(url));
	}

	public static String sendGETReturnString(String url) {
		return sendHttpRequest(url);
	}

	private static String sendHttpRequest(String url) {
		String result = "";// 访问返回结果
		BufferedReader read = null;// 读取访问结果
		try {
			createURLConnection(url);
			// 获取所有响应头字段
			/*
			 * Map<String, List<String>> map = connection.getHeaderFields(); //
			 * 遍历所有的响应头字段，获取到cookies等 for (String key : map.keySet()) {
			 * System.out.println(key + "--->" + map.get(key)); }
			 */
			// 定义 BufferedReader输入流来读取URL的响应
			read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;// 循环读取
			while ((line = read.readLine()) != null) {
				result += line;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (read != null) {// 关闭流
				try {
					read.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	// 创建URLConnection链接的静态方法
	public static boolean createURLConnection(String url) {
		boolean flag = false;
		try {
			// 创建url
			URL realurl = new URL(url);
			// 打开连接
			connection = realurl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("Accept-Charset", "UTF-8");
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立连接
			connection.connect();
			getHeaderFields();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	// 获得文件名字
	public String getFileName() {
		String fileName = "";
		try {
			fileName = connection.getHeaderField("Content-Disposition");
			fileName = URLDecoder.decode(fileName, "UTF-8");
			fileName = fileName.split(";")[1].substring(10).replaceAll("\"", "");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
		return fileName;
	}

	// 打印遍历所有的响应头字段，获取到cookies等
	public void printAllHeaderFields() {
		getHeaderFields();
		for (String key : headerFields.keySet()) {
			System.out.println(key + "--->" + headerFields.get(key));
		}
	}

	// 获得响应头数据
	public static void getHeaderFields() {
		if (headerFields == null) {
			headerFields = connection.getHeaderFields();
		}
	}

	// 保存在URLConnection中的文件
	public JSONObject saveFileByURLConnection(String savePathUrl) {
		return saveFile(savePathUrl, getFileName());
	}

	public JSONObject saveFileByURLConnection(String savePathUrl, String name) {
		return saveFile(savePathUrl, name);
	}

	private static JSONObject saveFile(String savePathUrl, String name) {
		JSONObject out = new JSONObject();
		InputStream is = null;
		OutputStream os = null;
		if (savePathUrl.indexOf("/") != 0) {
			savePathUrl = "/" + savePathUrl;
		}
		String realPath = savePathUrl;
		if (!realPath.contains(":")) {
			realPath = getProjectPath() + realPath;
		}
		try {
			String fileName = name;
			fileName = rename(realPath + "/" + fileName, fileName);
			// 输入流
			is = connection.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			File sf = new File(realPath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			os = new FileOutputStream(realPath + "/" + fileName);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			out.put("path", sf.getPath() + "/" + fileName);
			out.put("filename", fileName);
			out.put("relativePath", savePathUrl.substring(1) + "/" + fileName);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (!(is == null)) {
					is.close();
				}
				if (!(os == null)) {
					os.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return out;
	}

	// 判读文件名是否存在，存在就进行重命名
	public static String rename(String filePath, String fileName) {
		String out = "";
		File file = new File(filePath);
		if (file.isFile() && file.exists()) {// 判断文件是否存在
			if (fileName.matches("(.*) \\(\\d*\\)\\.(.*)")) {
				int lastLeft = fileName.lastIndexOf("(");
				int lastRight = fileName.lastIndexOf(")");
				long num = Long.parseLong(fileName.substring(lastLeft + 1, lastRight)) + 1;
				out = atStringInsertOther(fileName, "(" + num + ")", lastLeft, lastRight + 1);
			} else {
				int lastPoint = fileName.lastIndexOf(".");
				out = atStringInsertOther(fileName, " (1)", lastPoint, lastPoint);
			}
		} else {
			out = fileName;
		}
		return out;
	}

	// 在字符串中插入其它字符串
	public static String atStringInsertOther(String originStr, String insertStr, int begin, int end) {
		return originStr.substring(0, begin) + insertStr + originStr.substring(end);
	}

	// 获取当前项目真实路径
	public static String getProjectPath() {
		// 当前目录路径
		String currentPath = new NetworkCaughtUtil().getClass().getResource("").getFile().toString();
		return currentPath.substring(1, currentPath.indexOf("WEB-INF"));
	}
}
